/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anism.API;

import java.util.Collection;
import java.util.GregorianCalendar;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.anism.bean.EmployeeFacadeLocal;
import org.anism.business.IRequestStatus;
import org.anism.entity.Employee;
import org.anism.entity.HolidayRequest;
import org.anism.entity.RequestHistory;

/**
 *
 * @author user
 */
@Stateless
public class HolidayValidation implements HolidayValidationLocal {

    @EJB
    private AuthenticationLocal auth;
    @PersistenceContext(unitName = "Holidays2-ejbPU")
    private EntityManager em;
    @EJB
    private EmployeeFacadeLocal employeeFacade;

    @Override
    public Employee authenticate(final String employeeId, final String password) {
        return auth.authenticate(employeeId, password);
    }

    @Override
    public Collection<HolidayRequest> getAllHolidayRequests(String employeeId) {
        Employee employee = employeeFacade.getEmployeeForID(employeeId);
        return employee.getHolidayRequestCollection();
    }

    @Override
    public HolidayRequest getHolidayRequest(int requestCode) {
        return (HolidayRequest) em.createNamedQuery("HolidayRequest.findById").setParameter("id", requestCode).getSingleResult();
    }

    /**
     * 
     * @param request la requête à valider
     * @return true si validé, false si non validé
     */
    @Override
    public boolean validateRequest(HolidayRequest request) {
        Collection<RequestHistory> history = request.getRequestHistoryCollection();

        boolean isRHValidated = false;
        boolean isValidated = false;

        for (RequestHistory rh : history) {

            if (rh.getStatus().equals(IRequestStatus.REQUEST_STATUS_RH_VALIDATED)) {
                isRHValidated = true;
            }

            // si l'histo contient un état validation définitive -> ok, stop vérif, déjà validé
            if (rh.getStatus().equals(IRequestStatus.REQUEST_STATUS_VALIDATED)) {
                isValidated = true;
                break;
            }
        }

        if (isValidated) {
            return true;
        }

        if (isRHValidated) {
            RequestHistory newRequestHistory = new RequestHistory();
            newRequestHistory.setRequest(request);
            newRequestHistory.setStatus(IRequestStatus.REQUEST_STATUS_VALIDATED);
            newRequestHistory.setDate(GregorianCalendar.getInstance().getTime());

            // TODO: voir si on ajoute un commentaire dans la RequestHistory
//                newRequestHistory.setComment(null);
            return true;
        }
        return false;
    }
}
